Daush.Interpreter = {
    createOutput: function(){
	var e = document.createElement( 'div' );
	e.className = "output";
	return e;
    },
    mods:{},
    run:function( inputstr, callBack ){
	var arr = inputstr.split(" ");
	var cmd = arr[0];
	var args = arr.slice(1);

	if(!cmd){ callBack(); }
	console.debug("Running");
	if( !this.mods[cmd] ){
	    var e = this.createOutput();
	    e.innerHTML = "No command";
	    callBack( e );
	}else{
	    this.mods[cmd].run( args, callBack, this.errHandler );
	}
    },
    add_module: function(mod){
	this.mods[mod.name] = mod;

	//Also add aliases
	return true;
    },

    completeHandler: function( resultHTML ){
	console.debug("Complete");
    },
    errHandler : function ( errMsg ){
	console.debug("Err");
    }
};


var i = Daush.Interpreter;

var testmod = {
    name: "help",
    help: "Display command usages.",
    run:function(args, callback, errHandler){
	var result = Daush.Interpreter.createOutput();
	var mods = Daush.Interpreter.mods;

	var table = document.createElement('table');
	table.className = "help";
	result.appendChild(table);

	for(var i in mods){
	    var mod = mods[i];

	    var ele = document.createElement('tr');
	    var ele_name = document.createElement('td');
	    var ele_alias = document.createElement('td');
	    var ele_desc = document.createElement('td');

	    ele.appendChild( ele_name );
	    ele.appendChild( ele_desc );

	    ele_name.className = "info";

	    ele_name.innerHTML = mod.name;
	    ele_desc.innerHTML = mod.help;

	    table.appendChild( ele );
	}

	var out = document.createElement('div');
	out.innerHTML = result.innerHTML;

	callback(out);
    }
};
i.add_module( testmod) ;

function clone(obj){

    if(obj == null || typeof(obj) != 'object')

	return obj;

    if(obj.constructor == Array)

	return [].concat(obj);

    var temp = {};

    for(var key in obj)

	temp[key] = clone(obj[key]);

    return temp;

}

function alias( cmdObj, new_name ){
    var cmdLs = clone( cmdObj );
    cmdLs.name = new_name;
    Daush.Interpreter.add_module( cmdLs);
}

alias( testmod, "ls");
alias( testmod, "ll");

// Alias

/** Codes for test **/
/*

i.run("help me", function(arr){console.debug(arr);});
i.run("asdfasdf", function(arr){console.debug(arr);});
*/
